package com.doxiaopu.students.user.service.impl;

import com.doxiaopu.students.component.exception.*;
import com.doxiaopu.students.user.entity.PersonRelation;
import com.doxiaopu.students.user.entity.User;
import com.doxiaopu.students.user.mapper.UserMapper;
import com.doxiaopu.students.user.service.IUserService;
import com.doxiaopu.students.user.vo.OrganizationTypesVO;
import com.doxiaopu.students.utils.GetIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.*;

@Service
@Primary
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User reg(User user) throws DuplicateKeyException, InsertException {
        // 根据尝试注册的用户名查询用户数据
        User data = findByUsername(user.getUsername());
        //判断查询到的数据是否为null
        if(data ==null) {
            //是否已删除：否
            user.setIsDelete(0);
            //4项日志
            Date now = new Date();
            user.setCreatedUser(user.getUsername());
            user.setModifiedUser(user.getUsername());
            user.setCreatedTime(now);
            user.setModifiedTime(now);
            //是：用户名不存在，允许注册，则处理密码加密
            String salt= UUID.randomUUID().toString();
            String TUserId = UUID.randomUUID().toString();
            String srcpassword = user.getPassword();
            String mdpassword = getmd5password(srcpassword,salt);
            user.setPassword(mdpassword);
            user.setSalt(salt);
            user.setTUserId(TUserId);
            //生成随机昵称
            Random rand = new Random();
            int randNum = rand.nextInt(9999999)+10000000;
            String nickname = "Do"+ Integer.toString(randNum);
            user.setNickname(nickname);
            if(user.getTypes() == null ){
                user.setTypes(0);
            }
            //执行注册
            addNew(user);
            //--返回注册的用户对象
            return user;
        }else {
            //否；用户名已被占用，抛出DuplicateKeyException
            throw new DuplicateKeyException("用户名已存在");
        }
    }

    @Override
    public User login(String username, String password) throws PasswordNotMathException, UserNotFoundException {
        User data = findByUsername(username);
        if(data==null) {
            throw new UserNotFoundException("用户名不存在");
        }
        String salt = data.getSalt();
        String mdpassword = getmd5password(password,salt);
        if(data.getPassword().equals(mdpassword)){
            if(data.getIsDelete() ==1){
                throw new UserNotFoundException("登录失败！该账户已被删除");
            }
            data.setPassword(null);
            data.setSalt(null);
            return data;
        }else {
            throw new PasswordNotMathException("登录失败，密码错误");
        }
    }

    @Override
    public void changeInfo(User user) throws UpdateException {
        User data = getById(user.getId());
        if(data == null){
            throw new UserNotFoundException("修改用户资料失败，尝试修改的用户不存在");
        }
        user.setModifiedUser(data.getUsername());
        user.setModifiedTime(new Date());
        updateInfo(user);
    }

    @Override
    public User getInfo(Integer id) {
        User data = getById(id);
        return data;
    }
    //    获取所有用户信息
    @Override
    public Map<String, Object> getAllInfo(String phone,Integer types, Integer currentPage, Integer pageSize) {
        currentPage = (currentPage - 1) * pageSize;
        Map<String, Object> res = new HashMap<>();
        List<User> dota = getAllUserInfo(phone,types,currentPage,pageSize);
        Integer totle = selectTotle(types);
        res.put("dota", dota);
        res.put("totle", totle);
        return res;
    }

    @Override
    public Integer updateBalanceInfo(String TUserId, Integer add,Integer decrease,Integer id) {
        User createUser = userMapper.getById(id);
        Date now = new Date();
        User user = getBalanceByTUserId(TUserId);
        System.err.print("user:"+user);
        if(user.getBalance() == null) {
            Integer balance = add;
            System.err.print("balance:"+balance);
            user.setBalance(balance);
        }else {
            Integer balance = user.getBalance() + add - decrease;
            if(balance >=0) {
                System.err.print("balance:"+balance);
                user.setBalance(balance);
            }else {
                user.setBalance(0);
            }
        }
        user.setModifiedUser(createUser.getModifiedUser());
        user.setModifiedTime(now);
        user.setTUserId(TUserId);
        Integer row = updateBalance(user);
        System.err.print("row:"+row);
        return row;
    }

    @Override
    public List<User> getCommunityUserList(Integer id) {
        User user = userMapper.getById(id);
        System.err.print(user);
        if(user.getTypes().equals(2) || user.getTypes().equals(3)){
            user.setOrganizationTypes(1);
            return getAppCommunityUserInfo(user);
        }else {
            //判断是否已经有组织
            if(user.getMassOrganizationId() == null || user.getOrganizationTypes() ==null){
                return null;
            }else {
                //判断是否已经审核通过
                if(user.getOrganizationTypes().equals(1)){
                    return getAppCommunityUserInfo(user);
                }else {
                    return null;
                }
            }
        }
    }

    @Override
    public List<User> getApplyCommunityUserList(Integer id) {
        User user = userMapper.getById(id);
        List<User> data = getApplyUserInfo(user);
        //去除在申请列表中的会长
        for(int i=data.size()-1;i>=0;i--) {
            User item = data.get(i);
            if(user.getUsername().equals(item.getUsername())){
                data.remove(item);
            }
        }
        //判断是会长查看自己的申请信息
        if(user.getTypes().equals(2)) {
            return data;
        }else {
            return null;
        }
    }

    @Override
    public Integer updateOrgTypes(OrganizationTypesVO organizationTypesVO, Integer id) {
        User user = userMapper.getById(id);
        Date now = new Date();
        organizationTypesVO.setOrganizationTypes(1);
        organizationTypesVO.setModifiedUser(user.getUsername());
        organizationTypesVO.setModifiedTime(now);
        return updateOrganizationTypes(organizationTypesVO);
    }

    @Override
    public Integer addChatPersonRelation(Integer id, PersonRelation personRelation) {
        User user = userMapper.getById(id);
        Date now = new Date();
        GetIdUtil getIdUtil = new GetIdUtil();
        String messagePersonId = getIdUtil.getId();
        personRelation.setMessagePersonId(messagePersonId);
        personRelation.setCreatedUser(user.getNickname());
        personRelation.setModifiedUser(user.getNickname());
        personRelation.setCreatedTime(now);
        personRelation.setModifiedTime(now);
        Integer row = userMapper.addChatPersonRelation(personRelation);
        return row;
    }

    @Override
    public String checkRecivePsersonId(String sendPersonId ,String acceptPersonId) {
        List<PersonRelation> reciveUser = userMapper.getChatPersonRelationByMyId(sendPersonId);
        for (PersonRelation personRelation :reciveUser) {
            if(acceptPersonId.equals(personRelation.getAcceptPersonId())){
                return "已经是好友";
            }
        }
        return "不是好友";
    }


    /**
     * 获取加密密码
     * @param srcpassword 源密码
     * @param salt	UUID盐
     * @return 加密后的密码
     */
    private String getmd5password(String srcpassword,String salt) {
        //盐值 拼接 原密码 拼接 盐值
        String src = salt+srcpassword+salt;
        String MDpassword = src;
        //循环执行10次摘要规则
        for(int i=0;i<10;i++) {
            MDpassword = DigestUtils.md5DigestAsHex(MDpassword.getBytes());
        }
        //返回摘要结果
        return MDpassword;

    }
    /**
     * 插入用户数据
     *
     * @param user 用户数据
     * @return 受影响行数
     */
    private void addNew(User user){
        Integer rows = userMapper.addNewUser(user);
        if(rows!=1) {
            throw new InsertException("增加用户数据时出现未知错误");
        }
    }
    /**
     * 根据用户名查询用户数据
     *
     * @param username 用户名
     * @return 匹配用户名，没有用户匹配的数据，则返回NULL
     */
    private User findByUsername(String username){
        return userMapper.findByUsername(username);
    };
    /**
     * 修改个人用户资料
     * @param user
     */
    private void updateInfo(User user){
        Integer rows = userMapper.updateInfo(user);
        if (rows !=1){
            throw new UpdateException("更新用户时出现的异常");
        }
    };

    /**
     * 通过id查询用户数据
     * @param id
     * @return
     */
    private User getById(Integer id){
        return userMapper.getById(id);
    }

    /**
     * 根据用户类型查询所有的用户信息
     * @return 返回用户信息列表
     */
    private List<User> getAllUserInfo(String phone,Integer types,Integer currentPage,Integer pageSize){
        return userMapper.getAllUserInfo(phone,types,currentPage,pageSize);
    }
    /**
     * 查询用户的总条数
     * @return
     */
    private Integer selectTotle(Integer types){
        return userMapper.selectTotle(types);
    }
    /**
     * 更改用户余额
     * @param user
     * @return
     */
    private Integer updateBalance(User user){
        return userMapper.updateBalance(user);
    };
    /**
     * 获得用户的余额
     * @param TUserId
     * @return
     */
    private User getBalanceByTUserId(String TUserId){
        return userMapper.getBalanceByTUserId(TUserId);
    };
    /**
     * 查询组织所用成员
     * @param user
     * @return
     */
    private List<User> getAppCommunityUserInfo(User user){
        return userMapper.getAppCommunityUserInfo(user);
    };
    /**
     * 获取申请用户的所有信息
     * @param user
     * @return
     */
    private List<User> getApplyUserInfo(User user){
        return userMapper.getApplyUserInfo(user);
    };

    /**
     * 社团审核成员
     * @param organizationTypesVO
     * @return
     */
    private Integer updateOrganizationTypes(OrganizationTypesVO organizationTypesVO) {
        return userMapper.updateOrganizationTypes(organizationTypesVO);
    };
}
